package com.beifu.manager.api.controller.assetin;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.beifu.manager.api.domain.logon.MobileUserInfo;
import com.beifu.manager.model.*;
import com.utils.Constants;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.beifu.manager.api.common.PageInfo;
import com.beifu.manager.api.domain.spares.AssetInDetailResponse;
import com.beifu.manager.api.domain.spares.AssetInPageDetailResponse;
import com.beifu.manager.api.domain.spares.AssetInPageListResponse;
import com.beifu.manager.api.domain.spares.AssetInPlanDetailResponse;
import com.beifu.manager.api.domain.spares.AssetInRfId;
import com.beifu.manager.api.domain.spares.AssetInTruthDetailResponse;
import com.beifu.manager.api.domain.spares.AssetInTruthPageResponse;
import com.beifu.manager.api.domain.spares.AssetInTruthRequest;
import com.beifu.manager.api.domain.spares.AssetInUploadInfo;
import com.beifu.manager.model.AssetInExample.Criteria;
import com.beifu.manager.service.assetin.AssetInService;
import com.beifu.manager.service.assetintruth.AssetInTruthService;
import com.mds.manager.utils.DateUtils;
import com.utils.PageUtils;
import com.utils.ResponseHelp;

import net.sf.json.JSONObject;
import net.sf.json.util.JSONUtils;

/**
 * 
 * @author BaiBing
 *
 */
@RestController
@RequestMapping(value="/mobileserve/spares/api", produces = "application/json;charset=UTF-8")
public class SparesInListController {

	@Autowired
	private AssetInService assetInService;
	
	@Autowired
	private AssetInTruthService assetInTruthService;
	
    /**
     * 备品入库单列表
     * @param reqMap
     * @return
     */
    @RequestMapping(value="/getSparesInList", method= RequestMethod.POST)
    public String getSparesInList(@RequestBody Map<String, Object> reqMap) {
        // 接收pub和in区域的请求数据
        JSONObject jsonPub = JSONObject.fromObject(reqMap.get("pub"));
        JSONObject jsonIn = JSONObject.fromObject(reqMap.get("in"));

        String userId = "";
        String devID = "";
        String timestamp = "";
        
        if (!JSONUtils.isNull(jsonPub)) {
			userId = (String) jsonPub.get("userId");
			devID = (String) jsonPub.get("devID");
			timestamp = (String) jsonPub.get("timestamp");
		}
        
        if(JSONUtils.isNull(jsonIn)){
        	return ResponseHelp.responseApiErrorText("2222", "传入参数不能为空！");
        }

        if (null == jsonIn.get("pageIndex") || StringUtils.isBlank(jsonIn.get("pageIndex").toString())) {
            return ResponseHelp.responseApiErrorText("1111", "pageIndex不能为空！");
        }
        if (null == jsonIn.get("pageNumber") || StringUtils.isBlank(jsonIn.get("pageNumber").toString())) {
            return ResponseHelp.responseApiErrorText("1112", "pageNumber不能为空！");
        }

        String pageIndex = jsonIn.get("pageIndex").toString();
        String pageNumber = jsonIn.get("pageNumber").toString();

        Subject subject = SecurityUtils.getSubject();
        MobileUserInfo mobileUserInfo = (MobileUserInfo)subject.getPrincipal();

        List<AssetIn> list = new ArrayList<AssetIn>();

        AssetInExample example = new AssetInExample();
		Criteria criteria = example.createCriteria().andDestOrganizeIdEqualTo(Integer.valueOf(mobileUserInfo.getOrganizeId()));
		
		PageUtils Page = new PageUtils(pageIndex);
		Page.setLimit(Integer.valueOf(pageNumber));
		Page.setQueryParames(example);
		
		Page = assetInService.getAssetInPage(Page);
		list = (List<AssetIn>) Page.getList();
		
		boolean hasNextPage = false;
		int CountPage = Page.getCountPage();
		if(CountPage - Integer.valueOf(pageIndex) > 0){
			hasNextPage = true;
		}
		
        PageInfo pageInfo = new PageInfo();

        List<AssetInPageDetailResponse> assetsInList= assetIn2Response(list);
        AssetInPageListResponse assetInPageListResponse = new AssetInPageListResponse();
        assetInPageListResponse.setAssetsInList(assetsInList);
        
        pageInfo.setResult(assetInPageListResponse);
        pageInfo.setPageIndex(Integer.valueOf(pageIndex));
        pageInfo.setPageNum(Integer.valueOf(pageNumber));
        pageInfo.setHasNextPage(hasNextPage);
        return ResponseHelp.responseApiSuccessText(pageInfo);
    }

    
    private List<AssetInPageDetailResponse> assetIn2Response(List<AssetIn> assetInList){
    	List<AssetInPageDetailResponse> result = new ArrayList<AssetInPageDetailResponse>();
    	if(null != assetInList && assetInList.size() > 0){
    		for(AssetIn assetIn:assetInList){
    			AssetInPageDetailResponse assetInPageDetailResponse = new AssetInPageDetailResponse();
    			assetInPageDetailResponse.setAssetsInId(assetIn.getId()+"");
    			assetInPageDetailResponse.setStatus(assetIn.getStatus()+"");
    			result.add(assetInPageDetailResponse);
    		}
    	}
    	return result;
    }
    
    /**
     * 备品入库单详情
     * @param reqMap
     * @return
     */
    @RequestMapping(value="/getSpareInDetail")
    public String getSpareInDetail(@RequestBody Map<String, Object> reqMap){
    	// 接收pub和in区域的请求数据
        JSONObject jsonPub = JSONObject.fromObject(reqMap.get("pub"));
        JSONObject jsonIn = JSONObject.fromObject(reqMap.get("in"));

        String userId = "";
        String devID = "";
        String timestamp = "";
        
        if (!JSONUtils.isNull(jsonPub)) {
			userId = (String) jsonPub.get("userId");
			devID = (String) jsonPub.get("devID");
			timestamp = (String) jsonPub.get("timestamp");
		}
        
        if(JSONUtils.isNull(jsonIn)){
        	return ResponseHelp.responseApiErrorText("2222", "传入参数不能为空！");
        }

        if (jsonIn.get("assetsInId") == null) {
            return ResponseHelp.responseApiErrorText("1111", "入库单ID为空！");
        }
        
        String assetInId = (String)jsonIn.get("assetsInId");
        AssetIn assetIn = assetInService.getAssetInById(Integer.valueOf(assetInId));
        
        List<AssetInPlan> assetInPlans = assetIn.getAssetInPlans();
        List<AssetInPlanDetailResponse> assetInPlanList = new ArrayList<AssetInPlanDetailResponse>();

        AssetInDetailResponse assetInDetailResponse = new AssetInDetailResponse();
        assetInDetailResponse.setApplyName(assetIn.getCreateUserInfo().getUserName());//操作人
        assetInDetailResponse.setApplyDate(DateUtils.getDateToStr(assetIn.getInTime()));//操作时间
        assetInDetailResponse.setSumNum(getAssetInPlanSumNum(assetInPlans)+"");//总数量
        assetInPlanList = getAssetInPlanDetailResponse(assetInPlans);
        assetInDetailResponse.setAssetInPlanList(assetInPlanList);//入库类型列表
        
    	return ResponseHelp.responseApiSuccessText(assetInDetailResponse);
    }
    
    private  List<AssetInPlanDetailResponse> getAssetInPlanDetailResponse(List<AssetInPlan> assetInPlans){
    	List<AssetInPlanDetailResponse> assetInPlanList = new ArrayList<AssetInPlanDetailResponse>();
    	if(null != assetInPlans && assetInPlans.size() > 0){
    		for(AssetInPlan assetInPlan:assetInPlans){
    			AssetInPlanDetailResponse assetInPlanDetailResponse = new AssetInPlanDetailResponse();
    			assetInPlanDetailResponse.setAssetInPlanId(assetInPlan.getId()+"");
    			assetInPlanDetailResponse.setTypeName(assetInPlan.getAssetType() == null ?"":assetInPlan.getAssetType().getName());
    			assetInPlanDetailResponse.setTypeId(assetInPlan.getAssetType().getModelName() == null ?"":assetInPlan.getAssetType().getModelName());
    			assetInPlanDetailResponse.setNum(assetInPlan.getInCount()+"");
    			assetInPlanList.add(assetInPlanDetailResponse);
    		}
    	}
    	return assetInPlanList;
    }
    
    //计算备品入库总数量
    private int getAssetInPlanSumNum(List<AssetInPlan> assetInPlans){
    	Integer sumNum = new Integer(0);
    	for(AssetInPlan assetInPlan:assetInPlans){
    		sumNum = sumNum + assetInPlan.getInCount();
    	}
    	return sumNum.intValue();
    }
    
    
    /**
     * 分页查询备品入库单详情列表
     * @param reqMap
     * @return
     */
    @RequestMapping(value="/getSparesInTruthList", method= RequestMethod.POST)
    public String getSparesInTruthList(@RequestBody Map<String, Object> reqMap) {
        // 接收pub和in区域的请求数据
        JSONObject jsonPub = JSONObject.fromObject(reqMap.get("pub"));
        JSONObject jsonIn = JSONObject.fromObject(reqMap.get("in"));

        String userId = "";
        String devID = "";
        String timestamp = "";
        
        if (!JSONUtils.isNull(jsonPub)) {
			userId = (String) jsonPub.get("userId");
			devID = (String) jsonPub.get("devID");
			timestamp = (String) jsonPub.get("timestamp");
		}
        
        if(JSONUtils.isNull(jsonIn)){
        	return ResponseHelp.responseApiErrorText("2222", "传入参数不能为空！");
        }

        String assetInId =  jsonIn.get("assetsInId").toString();

        AssetInTruthExample  assetInTruthExample = new AssetInTruthExample();
        com.beifu.manager.model.AssetInTruthExample.Criteria criteria = assetInTruthExample.createCriteria();
        if(!StringUtils.isEmpty(assetInId)){
            criteria.andAssetInIdEqualTo(Long.valueOf(assetInId));
        }
        List<AssetInTruth> list =  assetInTruthService.getAssetInTruthByAssetInTruthExample(assetInTruthExample);

        AssetInTruthPageResponse assetInTruthPageResponse = new AssetInTruthPageResponse();
        assetInTruthPageResponse.setAssetInTruthList(getAssetInTruthDetailResponse(list));
        return ResponseHelp.responseApiSuccessText(assetInTruthPageResponse);

        /*if (null == jsonIn.get("pageIndex") || StringUtils.isBlank(jsonIn.get("pageIndex").toString())) {
            return ResponseHelp.responseApiErrorText("1111", "pageIndex不能为空！");
        }
        if (null == jsonIn.get("pageNumber") || StringUtils.isBlank(jsonIn.get("pageNumber").toString())) {
            return ResponseHelp.responseApiErrorText("1112", "pageNumber不能为空！");
        }

        String pageIndex = jsonIn.get("pageIndex").toString();
        String pageNumber = jsonIn.get("pageNumber").toString();
        
        String assetInId =  jsonIn.get("assetsInId").toString();
        
        
		
		AssetInTruthExample  assetInTruthExample = new AssetInTruthExample();
		com.beifu.manager.model.AssetInTruthExample.Criteria criteria = assetInTruthExample.createCriteria();
		if(!StringUtils.isEmpty(assetInId)){
			criteria.andAssetInIdEqualTo(Long.valueOf(assetInId));
		}
		
		PageUtils Page = new PageUtils(pageIndex);
		Page.setLimit(Integer.valueOf(pageNumber));
		Page.setQueryParames(assetInTruthExample);
		Page = assetInTruthService.getAssetInTruthPage(Page);
		
        
		List<AssetInTruth> list = (List<AssetInTruth>) Page.getList();
		
		boolean hasNextPage = false;
		int CountPage = Page.getCountPage();
		if(CountPage - Integer.valueOf(pageIndex) > 0){
			hasNextPage = true;
		}
		
        PageInfo pageInfo = new PageInfo();

        AssetInTruthPageResponse assetInTruthPageResponse = new AssetInTruthPageResponse();
        assetInTruthPageResponse.setAssetInTruthList(getAssetInTruthDetailResponse(list));

        pageInfo.setResult(assetInTruthPageResponse);
        pageInfo.setPageIndex(Integer.valueOf(pageIndex));
        pageInfo.setPageNum(Integer.valueOf(pageNumber));
        pageInfo.setHasNextPage(hasNextPage);
        return ResponseHelp.responseApiSuccessText(pageInfo);*/
    }
    
    private List<AssetInTruthDetailResponse> getAssetInTruthDetailResponse(List<AssetInTruth> assetInTruthList){
    	List<AssetInTruthDetailResponse> assetInTruthListResponse = new ArrayList<AssetInTruthDetailResponse>();
    	if(null != assetInTruthList && assetInTruthList.size() > 0){
    		for(AssetInTruth assetInTruth:assetInTruthList){
    			AssetInTruthDetailResponse assetInTruthDetailResponse = new AssetInTruthDetailResponse();
    			assetInTruthDetailResponse.setRfId(assetInTruth.getAssetInfoRfidCode());
    			String typeModelName = "";
    			if(assetInTruth.getAssetInfo()!=null && assetInTruth.getAssetInfo().getAssetBase()!=null
                             && assetInTruth.getAssetInfo().getAssetBase().getAssetType()!=null){
                    typeModelName = assetInTruth.getAssetInfo().getAssetBase().getAssetType().getModelName();
                }
                assetInTruthDetailResponse.setTypeModelName(typeModelName);
    			assetInTruthDetailResponse.setTypeName(assetInTruth.getAssetTypeName());
    			assetInTruthListResponse.add(assetInTruthDetailResponse);
    		}
    	}
    	return assetInTruthListResponse;
    }
    
    /**
     * 备品入库详情上传
     * @throws ParseException 
     */
    @RequestMapping(value="/uploadSparesInDetail")
    public String uploadSparesInDetail(@RequestBody Map<String, Object> reqMap) throws ParseException {
        // 接收pub和in区域的请求数据
        JSONObject jsonPub = JSONObject.fromObject(reqMap.get("pub"));
        JSONObject jsonIn = JSONObject.fromObject(reqMap.get("in"));
        
        String userId = "";
        String devID = "";
        String timestamp = "";
        if (!JSONUtils.isNull(jsonPub)) {
			userId = (String) jsonPub.get("userId");
			devID = (String) jsonPub.get("devID");
			timestamp = (String) jsonPub.get("timestamp");
		}
        if(JSONUtils.isNull(jsonIn)){
        	return ResponseHelp.responseApiErrorText("2222", "传入参数不能为空！");
        }
        
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("assetsInList", AssetInUploadInfo.class);
        map.put("rfIds", AssetInRfId.class);
        AssetInTruthRequest assetInTruthRequest = (AssetInTruthRequest)JSONObject.toBean(jsonIn, AssetInTruthRequest.class,map);

        
        Map<String,Object> paramMap = new HashMap<String,Object>();
        paramMap.put("assetInId", assetInTruthRequest.getAssetInId());//备品入库单编号
        paramMap.put("assetsInList", assetInTruthRequest.getAssetsInList());//备品入库上传列表
        paramMap.put("operatingUserId", userId);//操作员编号
        paramMap.put("operatingDeviceId", devID);//设备编号

        /*paramMap.put("rfIds", assetsInList);//rfId集合
        paramMap.put("operatingUserId", userId);//操作员编号
        paramMap.put("operatingDeviceId", devID);//设备编号
        paramMap.put("assetInId", assetInId);//备品入库单编号
        paramMap.put("assetInPlanId", assetInPlanId);//入库单计划id
*/
        try{
            Map<String,String> retMap = assetInService.saveAssetInTruth(paramMap);
        }catch(RuntimeException e){
            return ResponseHelp.responseApiErrorText(Constants.ErrorMessage.RETCODE0000006.getRetCode(),e.getMessage());
        }
        
        return ResponseHelp.responseApiSuccessText(null);
    }
    
}
